<template>
  <div class="activities-container">
    <h1>文化活动</h1>
    
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
        v-model="keyword"
        placeholder="请输入活动名称"
        clearable
        @input="handleSearch"
        prefix-icon="el-icon-search"
        style="width: 400px; margin-bottom: 20px;"
      ></el-input>
    </div>
    
    <!-- 活动列表 -->
    <div class="activity-list">
      <div class="activity-item" v-for="activity in activities" :key="activity.id">
        <img :src="activity.image" :alt="activity.title" class="activity-img">
        <div class="activity-content">
          <h3>{{ activity.title }}</h3>
          <p class="meta">时间：{{ activity.time }} | 地点：{{ activity.location }}</p>
          <p class="desc">{{ activity.description }}</p>
          <p class="quota">名额：{{ activity.quota }}</p>
          <el-button 
            type="primary" 
            @click="openForm(activity)"
            :disabled="isActivityExpired(activity.time)"
          >
            {{ isActivityExpired(activity.time) ? '报名已截至' : '立即报名' }}
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    
    <!-- 报名表单 -->
    <el-dialog v-model="dialogVisible" title="活动报名">
      <el-form :model="form">
        <el-form-item label="活动" :label-width="80">
          <el-input v-model="form.activityName" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="80" required>
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" :label-width="80" required>
          <el-input v-model="form.contact" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="80">
          <el-input v-model="form.remark" type="textarea" rows="2"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </el-dialog>
    
    <!-- 成功提示 -->
    <el-dialog v-model="successVisible" title="报名成功" :show-close="false">
      <div style="text-align: center; padding: 20px 0;">
        <el-icon class="success-icon"><CircleCheck /></el-icon>
        <p>报名成功！报名编号：{{ enrollNo }}</p>
        <p>状态：报名待审核</p>
        <p>结果将通过预留联系方式通知</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="successVisible = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { CircleCheck } from '@element-plus/icons-vue'
import { getActivities, enrollActivity } from '../api/activities'

// 数据
const activities = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(3)
const keyword = ref('')
const dialogVisible = ref(false)
const successVisible = ref(false)
const enrollNo = ref('')
const currentActivity = ref(null)

// 表单数据
const form = reactive({
  activityId: '',
  activityName: '',
  name: '',
  contact: '',
  remark: ''
})

// 判断活动是否过期
const isActivityExpired = (activityTime) => {
  const activityDate = new Date(activityTime)
  const now = new Date()
  return activityDate < now
}

// 加载活动列表
const loadActivities = async () => {
  try {
    const res = await getActivities({
      current: currentPage.value,
      size: pageSize.value,
      keyword: keyword.value
    })
    // 处理后端返回的标准格式数据
    if (res.code === 200 && res.data) {
      activities.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error('获取活动列表数据格式错误')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取活动列表失败，请稍后重试')
    console.error('活动列表加载失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  loadActivities()
}

// 当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadActivities()
}

// 打开报名表单
const openForm = (activity) => {
  currentActivity.value = activity
  form.activityId = activity.id
  form.activityName = activity.title
  form.name = ''
  form.contact = ''
  form.remark = ''
  dialogVisible.value = true
}

// 提交报名
const submit = async () => {
  // 简单验证
  if (!form.name || !form.contact) {
    ElMessage.warning('请填写必填项')
    return
  }
  
  try {
    const userInfo = {
      name: form.name,
      contact: form.contact,
      remark: form.remark
    }
    const res = await enrollActivity(form.activityId, userInfo)
    
    if (res.code === 200) {
      enrollNo.value = res.data?.enrollNo || Math.random().toString(36).substr(2, 9).toUpperCase()
      dialogVisible.value = false
      successVisible.value = true
    } else {
      ElMessage.error(res.message || '报名失败')
    }
  } catch (error) {
    console.error('活动报名错误:', error)
    ElMessage.error(error.message || '报名失败')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadActivities()
})
</script>

<style scoped>
.activities-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.search-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.activity-item {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 20px;
}

.activity-img {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.activity-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.activity-content h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.meta, .desc, .quota {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.activity-content .el-button {
  align-self: flex-start;
  margin-top: 10px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
  margin-bottom: 16px;
}

/* 响应式 */
@media (max-width: 768px) {
  .search-container .el-input {
    width: 100% !important;
  }
  
  .activity-item {
    flex-direction: column;
  }
  
  .activity-img {
    width: 100%;
    height: 200px;
  }
}
</style>